import { NextRequest, NextResponse } from 'next/server';
import { writeFile, mkdir } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';

// 新的配置方式
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(request: NextRequest) {
    try {
        const formData = await request.formData();
        const file = formData.get('file') as File;
        
        if (!file) {
            return NextResponse.json(
                { error: '没有找到文件' },
                { status: 400 }
            );
        }

        const bytes = await file.arrayBuffer();
        const buffer = Buffer.from(bytes);

        // 生成唯一的文件名
        const uniqueFilename = `${uuidv4()}-${file.name}`;
        const uploadDir = join(process.cwd(), 'public', 'uploads');
        
        // 确保上传目录存在
        try {
            await mkdir(uploadDir, { recursive: true });
        } catch (err) {
            console.error('创建目录失败:', err);
        }

        const filepath = join(uploadDir, uniqueFilename);

        // 保存文件
        await writeFile(filepath, buffer);
        console.log('文件已保存到:', filepath);

        // 返回可访问的URL路径
        return NextResponse.json({ url: `/uploads/${uniqueFilename}` });
    } catch (error) {
        console.error('Upload error:', error);
        return NextResponse.json(
            { error: '文件上传失败', details: error instanceof Error ? error.message : String(error) },
            { status: 500 }
        );
    }
} 